import axios from 'axios';
import { responseType } from '@/constans/response-type';

// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // 请求路径
  timeout: 10 * 1000, // 请求超时时间
});

// 添加请求拦截
instance.interceptors.request.use(
  (config) => {
    // const token = getToken()
    // if (token) {
    //     config.headers['Authorization'] = `Bearer ${token}`
    // }
    return config;
  },
  (error) => {
    console.error(error);
    return Promise.reject(error);
  },
);

let logoutFlag = 0;
// 添加响应拦截
instance.interceptors.response.use(
  (response) => {
    const data = response.data;
    const code = data.code;
    if (data instanceof Blob) {
      // 文件
      return Promise.resolve(data);
    } else if (code === '200') {
      return Promise.resolve(data.result);
    } else if (code === 'NOT_LOGIN') {
      if (logoutFlag === 0) {
        logoutFlag++;
        $alert('登录状态已过期，请重新登录！', '系统提示', {
          confirmButtonText: '重新登录',
          type: 'warning',
          showClose: false,
        }).then(() => {
          // 退出登录
          // logout()
          // logoutFlag = 0
        });
      }
      return Promise.reject(data);
    } else {
      if (data.message) {
        $message.error(data.message);
      }
      return Promise.reject(data);
    }
  },
  (error) => {
    const response = error.response;
    let msg = null;
    if (response) {
      if (response.data && response.data.message) {
        msg = response.data.message;
      } else {
        msg = responseType[response.status] || '未知的异常！';
      }
    } else {
      msg = responseType[error.code || error.message] || '未知的异常！';
    }
    $message.error(msg);
    return Promise.reject(error);
  },
);

export default instance;
